package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.OffDaysContent;
import com.isunland.managesystem.entity.OffDetailContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import org.apache.http.Header;
import org.json.JSONException;

/**
 * Created by lenovo on 2016/4/1.
 * 可用调休申请
 */
@SuppressWarnings({ "deprecation", "FieldCanBeLocal" }) public class CheckOffFragment
    extends CheckDetailFragment implements View.OnClickListener {
  private static final int CHOOSE_FILE = 0;
  private static final int REQUEST_TYPE = 1;
  private static final int REQUEST_TRIP = 2;
  private EditText etOffReason;//原因事由
  private TextView tvOffType;//调休类型
  private EditText tvOffDays;//申请天数
  private TextView tvRelateTrip;//关联差旅单
  private TextView tvTripDetail;//差旅单详情
  private TextView tvHasCheckOff;//已申请的调休
  private TextView tvPostOff;//可用带薪假
  private TextView tvUsableOff;//可用调休假
  private LinearLayout llExtraFileCheckOff;//添加附件
  private TextView tvExtraFileCheckOff;//附件显示
  //    private TextView tvRestMax;//调休上限(天)
  private String mPath;
  private String mChoseFileName;

  private String mOffTypeId;//调休类型
  //单选差旅单
  private String btripListCode;//  关联差旅单id
  private String tripQuotesCode;//  关联差旅单id,带单引号
  private String btripListName;  //  关联差旅单的出差事由
  private CurrentUser mUser;
  private BaseVolleyActivity mActivity;
  //详情返回的附件
  private String filePath = "";
  private String fileOriginalName = "";

  //    //多选差旅单
  //    private String tripNames="";//  关联差旅单的出差事由
  //    private String tripIds="";//  关联差旅单id
  @Override public void onCreate(Bundle savedInstanceState) {
    mUser = CurrentUser.newInstance(getActivity());
    //获取可用调休天数
    //        volleyPostGetDays();
    mActivity = (BaseVolleyActivity) getActivity();
    super.onCreate(savedInstanceState);
  }

  private void volleyPostGetDays() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_OFF_DAYS);
    HashMap<String, String> params = new HashMap<>();
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        OffDaysContent content = new Gson().fromJson(arg0, OffDaysContent.class);
        tvUsableOff.setText(content.getRestDays());
        tvPostOff.setText(content.getWageDays());
        //                tvRestMax.setText(getString(R.string.restMaxValue, content.getRestMaxValue()));
      }
    });
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    setTitleCustom(R.string.requisitionOff);
    View v = inflater.inflate(R.layout.fragmet_check_off, container, false);
    findViews(v);
    initDetailData();
    return v;
  }

  private void findViews(View v) {
    etOffReason = (EditText) v.findViewById(R.id.et_offReason);
    tvOffType = (TextView) v.findViewById(R.id.tv_offType);
    tvOffDays = (EditText) v.findViewById(R.id.tv_offDays);
    tvRelateTrip = (TextView) v.findViewById(R.id.tv_relateTrip);
    tvTripDetail = (TextView) v.findViewById(R.id.tv_tripDetail);
    tvHasCheckOff = (TextView) v.findViewById(R.id.tv_hasCheckOff);
    tvPostOff = (TextView) v.findViewById(R.id.tv_postOff);
    tvUsableOff = (TextView) v.findViewById(R.id.tv_usableOff);
    tvExtraFileCheckOff = (TextView) v.findViewById(R.id.tv_extraFile_checkOff);
    llExtraFileCheckOff = (LinearLayout) v.findViewById(R.id.ll_extraFile_checkOff);
    //        tvRestMax= (TextView) v.findViewById(R.id.tv_restMax);

    LogUtil.i("mFileUrl==" + mFileUrl);
    tvOffType.setOnClickListener(this);
    tvRelateTrip.setOnClickListener(this);
    tvTripDetail.setOnClickListener(this);
    tvHasCheckOff.setOnClickListener(this);
    llExtraFileCheckOff.setOnClickListener(this);

    //        if (mMenuType == EDIT) {
    tvExtraFileCheckOff.setOnClickListener(new View.OnClickListener() {

      @Override public void onClick(View v) {
        if (!TextUtils.isEmpty(mFileUrl)) {

          ExtraDownLoadDialogFragment dialog =
              ExtraDownLoadDialogFragment.newInstance("", mFileUrl);
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.show(fm, "");
        }
      }
    });
    //        }
    if (mMenuType == WAIT_CHECK || mMenuType == CHECK_PASS) {
      etOffReason.setEnabled(false);
      tvOffType.setEnabled(false);
      tvOffDays.setEnabled(false);
      tvRelateTrip.setEnabled(false);
      llExtraFileCheckOff.setEnabled(false);
    }
    if (mMenuType == ADD) {
      //获取可用调休天数
      volleyPostGetDays();
    }
  }

  private void initDetailData() {
    if (mMenuType != ADD) {
      volleypostInit();
    }
  }

  private void volleypostInit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("attendType", mType);
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String response) {
        LogUtil.i("initTripResponse=" + response);
        volleyPostGetDays();
        MyUtils.dismissDialog();
        try {
          OffDetailContent content = new Gson().fromJson(response, OffDetailContent.class);
          filePath = content.getFilePath();
          fileOriginalName = content.getFileOriginalName();
          //初始化详情界面
          mOffTypeId = content.getHolyKindCode();
          btripListCode = content.getBtripListCode();
          btripListName = content.getBtripListName();
          if (!TextUtils.isEmpty(btripListCode)) {
            //带单引号的
            if (btripListCode.contains("'")) {
              tripQuotesCode = btripListCode;
            } else {
              tripQuotesCode = "'" + btripListCode.replaceAll(",", "','") + "'";
            }
          } else {
            tripQuotesCode = btripListCode;
          }
          etOffReason.setText(content.getHolyDesc());//原因事由
          HashMap<String, String> map = CheckListFragment.mapOffType;
          String kindName = map.get(content.getHolyKindCode());
          tvOffType.setText(kindName);//调休类型
          tvOffDays.setText(content.getHolyDays());//申请天数
          tvRelateTrip.setText(content.getBtripListName());//关联差旅单

          tvExtraFileCheckOff.setText(content.getFileOriginalName());//附件名字
          mFileUrl = content.getFilePath();
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
        ToastUtil.show(R.string.noConnectionToServer);
      }
    });
  }
  //保存

  @Override protected void volleyPostSave(String type) {
    String url = ApiConst.URL_REQUISITION_SAVE_OR_RUN;
    RequestParams params = new RequestParams();

    if (mMenuType != ADD) {

      params.put("id", mId);
      if (TYPE_RUN.equals(type)) {
        params.put("isList", "0");
      }
    }
    if ("abort".equalsIgnoreCase(mDataStatus)) {
      params.put("dataStatus", "new");
    }
    params.put("holyKindCode", mOffTypeId);
    params.put("holyDays", tvOffDays.getText().toString());
    params.put("holyDesc", etOffReason.getText().toString());
    params.put("btripListCode", btripListCode);
    params.put("btripListName", btripListName);
    params.put("staffId", mUser.getJobNumber());
    params.put("staffName", mUser.getRealName());
    params.put("remark", "可用调休申请");
    params.put("attendType", "usableExchange");//固定值
    params.put("saveOrRun", type);//保存：save  启动流程：run
    if (mPath != null) {
      try {
        params.put("myfiles", new File(mPath));
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        ToastUtil.show(R.string.fileNotFound);
        }
      }

    if (mMenuType != ADD) {
        //文件名和路径,默认都传
        params.put("fileOriginalName", fileOriginalName);
        params.put("filePath", filePath);
      }
    LogUtil.i("overParams=" + params.toString());
    if (TYPE_RUN.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    }
    if (TYPE_SAVE.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    }

    DefaultAsyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {

      @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        LogUtil.i("response===" + new String(response));
        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage =
              new Gson().fromJson(new String(response), SuccessMessage.class);

          String successType = successsMessage.getResult();
          LogUtil.i("result="
              + successsMessage.getResult()
              + ",message="
              + successsMessage.getMessage()
              + ",cause="
              + successsMessage.getCause());
          switch (successType) {
            case "1":
              getActivity().setResult(Activity.RESULT_OK);
              ToastUtil.show(R.string.success_operation);
              getActivity().finish();
              break;
            case "0":
              showErrorDialog(successsMessage.getMessage());
              break;
            default:
              ToastUtil.show(R.string.failure_operation);
              break;
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
        LogUtil.e("VolleyError", arg3);
        MyUtils.dismissDialog();
        ToastUtil.show(R.string.failure_operation);
      }
    });
  }

  @Override protected boolean isCorrectInput() {
    if (TextUtils.isEmpty(etOffReason.getText().toString())) {
      ToastUtil.show(R.string.no_content);
      return false;
    }
    if (TextUtils.isEmpty(tvOffType.getText().toString())) {
      ToastUtil.show(R.string.OffTypeHint);
      return false;
    }
    if (TextUtils.isEmpty(tvOffDays.getText().toString())) {
      ToastUtil.show(R.string.offDaysHint);
      return false;
    }

    return true;
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      //调休类型
      case R.id.tv_offType:
        showDialog(REQUEST_TYPE);
        break;
      //关联差旅单
      case R.id.tv_relateTrip:
        //                showDialog(REQUEST_TRIP,null);
        //关联差旅单--- 多选列表
        Intent trip = new Intent(getActivity(), TripMultipleListActivity.class);
        startActivityForResult(trip, REQUEST_TRIP);
        break;
      //差旅单详情
      case R.id.tv_tripDetail:
        //                if (TextUtils.isEmpty(btripListCode)){
        //                    ToastUtil.show(R.string.noRelateTrip);
        //                }else {
        //                    Intent detail=new Intent(getActivity(),CheckedOffTripDetailActivity.class);
        //                    detail.putExtra(CheckedOffTripDetailFragment.EXTRA_ITEM,btripListCode);
        //                    startActivity(detail);
        //                }
        //查看多选差旅单列表
        if (TextUtils.isEmpty(btripListCode)) {
          ToastUtil.show(R.string.noRelateTrip);
        } else {
          //关联差旅单--- 多选列表
          Intent tripDetail = new Intent(getActivity(), TripMultipleListActivity.class);
          tripDetail.putExtra(TripMultipleListFragment.EXTRA_TRIP_IDS, tripQuotesCode);
          startActivity(tripDetail);
        }

        break;
      //已申请的调休
      case R.id.tv_hasCheckOff:
        if (TextUtils.isEmpty(btripListCode)) {
          ToastUtil.show(R.string.noRelateTrip);
        } else {
          Intent i = new Intent(getActivity(), CheckedOffListActivity.class);
          i.putExtra(CheckedOfflistFragment.EXTRA_CODES, tripQuotesCode);
          startActivity(i);
        }
        break;

      //附件
      case R.id.ll_extraFile_checkOff:
        chooseFileDialog();
        break;
      default:
        break;
    }
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;

    switch (requestCode) {
      //调休类型
      case REQUEST_TYPE:

        dialog = new ChooseOffTypeDialogFragment();
        break;
      //关联差旅单
      case REQUEST_TRIP:
        dialog = new ChooseTripDialogFragment();
        break;

      default:
        break;
    }
    if (dialog == null) return;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    dialog.setTargetFragment(CheckOffFragment.this, requestCode);
    dialog.show(fm, "");
  }

  /**
   * 选择附件
   */
  private void chooseFileDialog() {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    dialog = new CompanyForumTopicFileDialogFragment();
    dialog.setTargetFragment(CheckOffFragment.this, CHOOSE_FILE);
    dialog.show(fm, "");
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", mType + "#" + mId);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            getActivity().setResult(Activity.RESULT_OK);
            ToastUtil.show(R.string.success_operation);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  /**
   * 处理返回按钮和返回的附件
   */
  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    // 添加附件
    if (requestCode == CHOOSE_FILE && data != null) {
      mPath = data.getStringExtra(CompanyForumTopicFileDialogFragment.EXTRA_RESULT);
      LogUtil.i("mPath=====" + mPath);
      if (mPath != null) {
        mChoseFileName = FileUtil.getFileNameByFilePath(mPath);
        tvExtraFileCheckOff.setText(mChoseFileName);
      }
    }

    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      volleyPostSave(TYPE_RUN);
    }

    //调休类型

    if (requestCode == REQUEST_TYPE && data != null) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      String mOffTypeName = customer.getName();
      mOffTypeId = customer.getId();
      tvOffType.setText(mOffTypeName);
    } //关联差旅单
    if (requestCode == REQUEST_TRIP && data != null) {
      //单选
      //            CustomerDialog customer = (CustomerDialog) data
      //                    .getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      //            btripListName=customer.getName();
      //            btripListCode=customer.getId();
      //            LogUtil.i("差旅单=="+btripListName+",,,,"+btripListCode);
      //            tvRelateTrip.setText(btripListName);

      //多选，，差旅单
      btripListName = data.getStringExtra(TripMultipleListFragment.EXTRA_TRIP_NAMES);
      btripListCode = data.getStringExtra(TripMultipleListFragment.EXTRA_TRIP_IDS);
      tripQuotesCode = "'" + btripListCode.replaceAll(",", "','") + "'";
      LogUtil.i("tripQuotesCode===" + tripQuotesCode);
      tvRelateTrip.setText(btripListName);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
